# -*- coding: utf-8 -*-
import os
from django.core.exceptions import PermissionDenied
from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template.context import RequestContext
from django.views.generic.dates import MonthArchiveView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from repairs.filter import Reader, Filter, Writer, R_Filter
from main.models import Unit, Employee, XLS_templates
from repairs.forms import R_CreateForm
from repairs.models import Repair, Compensation, RepairWorkers
import datetime as _date
import xlrd
from xlutils.copy import copy
from xlwt import XFStyle, Borders, Font, Alignment
from xlutils.filter import process
from xlwt.Style import easyxf
#---------------------------------- o_O --------------------------------------------------#

def add_worker(request, r_id, u_id):
    r = get_object_or_404(Repair, pk=r_id)
    if r.give_access or request.user.is_superuser:
        u= get_object_or_404(Unit, pk=u_id)
        if u in request.user.get_profile().unit_access.all():
            if request.POST:
                list = request.POST.getlist(u'worker_comp')
                for item in list:
                    d_count = int(item.split(',')[1])
                    if not int(item.split(',')[2]):
                        try:
                            obj = RepairWorkers.objects.get(repair=r, employee__id=int(item.split(',')[0]), date=r.get_dates()[d_count])
                            obj.delete()
                        except RepairWorkers.DoesNotExist:
                            pass

                    else:
                        obj, created = RepairWorkers.objects.get_or_create(repair=r, employee=Employee.objects.get(id=int(item.split(',')[0])), \
                            date=r.get_dates()[d_count], defaults={'compensation': Compensation.objects.get(id=item.split(',')[2])})
                        if not created and obj.compensation != Compensation.objects.get(id=item.split(',')[2]):
                            obj.compensation=Compensation.objects.get(id=item.split(',')[2])
                            obj.save()

            qs=[]
            for i in u.get_employees():
                qqs={}
                qqs['d_comp']=[]
                for d in r.get_dates():
                    qqs['worker']=i
                    try:
                        qqs['d_comp'].append(RepairWorkers.objects.get(repair=r, employee=i, date=d).compensation)
                    except RepairWorkers.DoesNotExist:
                        qqs['d_comp'].append(0)
                qs.append(qqs)

            return render_to_response('repairs/add.html', {'qs':qs, 'repair':r, 'unit':u, 'choices':Compensation.objects.all()}, \
                 context_instance=RequestContext(request))
        else:
            raise Http404
    else:
        raise Http404


#-------------------------------------------------Отчет о ремонте -------------------------------------------------------------

def exportexcel(request, repair):

    #-------------------------STyle-----------------------
    fnt = Font()
    fnt.name = 'Arial'
    borders = Borders()
    borders.left = Borders.THIN
    borders.right = Borders.THIN
    borders.top = Borders.THIN
    borders.bottom = Borders.THIN
    alignment = Alignment()
    alignment.horz = Alignment.HORZ_LEFT
    style = XFStyle()
    style.font = fnt
    style.borders = borders
    #-------------------------EndSTyle-----------------------

    obj = Repair.objects.get(pk=repair)
    dates = obj.get_dates()
    dates_iso = obj.get_dates_iso()

    w_list =[]
    for d in obj.get_dates():
        w_list.append(len(obj.repairworkers_set.filter(repair=obj, date=d))) #получаем список рабочих по дням для добавления строк в шаблон


    objecd = XLS_templates.objects.get(name=u"R_O")

    process(Reader(dates_iso,objecd),Filter(w_list), Writer()) # из шаблона делаем рабочий документ с кол. листов = количеству дат.
    rb = xlrd.open_workbook('temp.xls',on_demand=True,formatting_info=True) # открываем его, сохраняя стиль
    wb = copy(rb) # копируем т.к. rb только для чтения

    start_row=16 # по факту  ) )

    #------------------------------------------Writing XLS ------------------------------------------------------#
    for sheet_index in range(rb.nsheets):
        sheet = wb.get_sheet(sheet_index)
        
        sheet.write(15, 5, dates_iso[sheet_index],easyxf('font: bold True, height 300, name Arial;' 'borders: left thin, right thin,\
                    top thin, bottom thin;' "align: horiz centre, vert centre"))
        sheet.write(15, 6, dates_iso[sheet_index],easyxf('font: bold True, height 300, name Arial;' 'borders: left thin, right thin,\
                    top thin, bottom thin;'))
        cnt = 1
        r_workers = obj.repairworkers_set.filter(repair=obj, date=dates[sheet_index]).order_by('employee__unit')
        for stringus in r_workers:
            sheet.write(start_row+cnt, 0, cnt, style)
            sheet.write(start_row+cnt, 1, stringus.employee.__unicode__(), style)
            sheet.write(start_row+cnt, 2, stringus.employee.tabel_number, style)
            sheet.write(start_row+cnt, 3, stringus.employee.actual_unit.abb, style)
            sheet.write(start_row+cnt, 6, stringus.compensation.title, style)
            cnt=cnt+1
        sheet.write(start_row+cnt, 5, len(r_workers),easyxf('font: bold True, height 260, name Arial;' 'borders: left thin, right thin,\
                    top thin, bottom thin;' "align: horiz centre, vert centre"))

    fname = 'Ремонт.Отчёт-%s.%s.%s.xls' % (obj.start.day, obj.start.month, obj.start.year)
    response = HttpResponse(mimetype="application/vnd.ms-excel")
    response['Content-Disposition'] = 'attachment; filename=%s' % fname
    wb.save(response)
    return response
#------------------------------------Наряд-разрешение-------------------------------------------------------------------

def exportexcel_root(request, repair):
#-------------------------STyle-----------------------
    fnt = Font()
    fnt.name = 'Arial'
    borders = Borders()
    borders.left = Borders.THIN
    borders.right = Borders.THIN
    borders.top = Borders.THIN
    borders.bottom = Borders.THIN
    alignment = Alignment()
    alignment.horz = Alignment.HORZ_LEFT
    style = XFStyle()
    style.font = fnt
    style.borders = borders
    #-------------------------EndSTyle-----------------------

    obj = Repair.objects.get(pk=repair)
    dates = obj.get_dates()
    dates_iso = obj.get_dates_iso()

    w_list =[]
    for d in obj.get_dates():
        w_list.append(len(obj.repairworkers_set.filter(repair=obj, date=d))) 


    objecd = XLS_templates.objects.get(name=u"R_F")

    process(Reader(dates_iso,objecd),R_Filter(), Writer()) # из шаблона делаем рабочий документ с кол. листов = количеству дат.
    rb = xlrd.open_workbook('temp.xls',on_demand=True,formatting_info=True) # открываем его, сохраняя стиль
    wb = copy(rb) # копируем т.к. rb только для чтения

#------------------------------------------Writing XLS ------------------------------------------------------#
    start_row = 5
    start_row1 = 1
    
    for sheet_index in range(rb.nsheets):
        sheet = wb.get_sheet(sheet_index)

        sheet.write(6, 4, dates[sheet_index].strftime("%d.%m.%Y"),easyxf('font: bold True, height 200, name Arial;' 'borders: left thin, right thin,\
                    top thin, bottom thin;' "align: horiz centre, vert centre"))
        sheet.write(6, 5, dates[sheet_index],easyxf('font: bold True, height 200, name Arial;' 'borders: left thin, right thin,\
                    top thin, bottom thin;' "align: horiz centre, vert centre"))
        sheet.write(6, 6, dates[sheet_index],easyxf('font: bold True, height 200, name Arial;' 'borders: left thin, right thin,\
                    top thin, bottom thin;' "align: horiz centre, vert centre"))
        sheet.write(6, 7, dates[sheet_index],easyxf('font: bold True, height 200, name Arial;' 'borders: left thin, right thin,\
                    top thin, bottom thin;' "align: horiz centre, vert centre"))
        sheet.write(6, 7, dates[sheet_index],easyxf('font: bold True, height 200, name Arial;' 'borders: left thin, right thin,\
                    top thin, bottom thin;' "align: horiz centre, vert centre"))
        cnt = 1
        r_workers = obj.repairworkers_set.filter(repair=obj, date=dates[sheet_index]).order_by('employee__unit')
        for stringus in r_workers:
            sheet.write(start_row+cnt, 0, cnt, style)
            sheet.write(start_row+cnt, 1, stringus.employee.__unicode__(), style)
            sheet.write(start_row1+cnt, 10, stringus.employee.tabel_number, style)
            sheet.write(start_row1+cnt, 11, stringus.employee.__unicode__(), style)
            cnt=cnt+1
        sheet.write(start_row+cnt, 5, len(r_workers),easyxf('font: bold True, height 260, name Arial;' 'borders: left thin, right thin,\
                    top thin, bottom thin;' "align: horiz centre, vert centre"))

    fname = 'Ремонт.Наряд-разрешение-%s.%s.%s.xls' % (obj.start.day, obj.start.month, obj.start.year)
    response = HttpResponse(mimetype="application/vnd.ms-excel")
    response['Content-Disposition'] = 'attachment; filename=%s' % fname
    wb.save(response)
    return response


class RmonthListView(MonthArchiveView):

    def get_dated_items(self):
        year = int(self.get_year())
        month = int(self.get_month())
        day = _date.datetime.now().day

        months_choices = []
        for i in range(1,13):
            months_choices.append(_date.date(year, i, 1))

        next_year=None
        previous_year=None

        if year > 2006:
            previous_year=year-1
        if year < _date.datetime.now().year+1:
            next_year=year+1

        if year < 2006 or year > _date.datetime.now().year+1:
            raise Http404

        try:
            date = _date.date(year, month, day)
        except ValueError:
            raise Http404

        date_field = self.get_date_field()

        lookup_kwargs = {
            '%s__year' % date_field: date.year,
            '%s__month' % date_field: date.month,
        }
        qs = self.get_dated_queryset(**lookup_kwargs)

        return (None, qs, {
            'month': date,
            'previous_month': self.get_previous_month(date),
            'next_month': self.get_next_month(date),
            'm_list':months_choices,
            'next_year':next_year,
            'previous_year':previous_year,
        })

class RmonthList(RmonthListView):
    model = Repair
    date_field = 'start'
    template_name = 'repairs/repairs_list.html'
    allow_empty = True
    allow_future = True

class RthismonthListList(RmonthList):
    def get_dated_items(self):
        self.month = _date.datetime.now().month
        self.day = _date.datetime.now().day
        self.year = _date.datetime.now().year
        return super(RthismonthListList, self).get_dated_items()



class RepairCreateView(CreateView):
    template_name = 'repairs/repair_create.html'
    success_url = '/repairs/list/'
    form_class = R_CreateForm

    def get(self, request, *args, **kwargs):
        if request.user.has_perm('repair.add_repair') or request.user.is_superuser:
            return super(RepairCreateView, self).get(request, *args, **kwargs)
        else:
            raise PermissionDenied


class RepairUpdateView(UpdateView):
    form_class = R_CreateForm
    template_name = 'repairs/repair_update.html'
    success_url = '/repairs/list/'
    queryset = Repair.objects.all()

    def get(self, request, *args, **kwargs):
        if request.user.has_perm('repair.add_repair') or request.user.is_superuser:
            return super(RepairUpdateView, self).get(request, *args, **kwargs)
        else:
            raise PermissionDenied


class RepairDeleteView(DeleteView):
    success_url = '/repairs/list/'
    queryset = Repair.objects.all()

    def get(self, request, *args, **kwargs):
        if request.user.has_perm('repair.add_repair') or request.user.is_superuser:
            return super(RepairDeleteView, self).get(request, *args, **kwargs)
        else:
            raise PermissionDenied